#!/bin/sh

. /etc/functions.sh

local trueusername
local truepassword
local time

config_load truewifi
config_get trueusername setting username
config_get truepassword setting password
config_get time setting time

time=$time"m"
sleep 10

logout() {
	curl --user-agent "Mozilla/5.0 (X11; Linux i686; rv:12.0) Gecko/20100101 Firefox/12.0" --cookie /tmp/cookiejar.txt --cookie-jar /tmp/cookiejar.txt --insecure "https://portal.trueinternet.co.th/wifiauthen/logout_result.php"
}

login() {
	if [ "$parameter" ]; then
		curl --user-agent "Mozilla/5.0 (X11; Linux i686; rv:12.0) Gecko/20100101 Firefox/12.0" --cookie /tmp/cookiejar.txt --cookie-jar /tmp/cookiejar.txt --connect-timeout 5 --location --insecure --data "param=$parameter" 'https://portal.trueinternet.co.th/wifiauthen/web/wifi-logout-success.php?param=$parameter'
	fi
	local param=$(curl -iI www.google.com |grep login |sed -e 's/.*login.do?//')
	parameter=$(curl --user-agent "Mozilla/5.0 (X11; Linux i686; rv:12.0) Gecko/20100101 Firefox/12.0" --location --cookie /tmp/cookiejar.txt --cookie-jar /tmp/cookiejar.txt --insecure "https://portal.trueinternet.co.th/wifiauthen/login.do?$param" | grep param= | sed -e 's/.*param=//' -e 's/\".*>//')
	curl --user-agent "Mozilla/5.0 (X11; Linux i686; rv:12.0) Gecko/20100101 Firefox/12.0" --location --cookie /tmp/cookiejar.txt --cookie-jar /tmp/cookiejar.txt  --insecure "https://portal.trueinternet.co.th/wifiauthen/web/wifi-login.php?param=$parameter"
	curl --user-agent "Mozilla/5.0 (X11; Linux i686; rv:12.0) Gecko/20100101 Firefox/12.0" --referer "https://portal.trueinternet.co.th/wifiauthen/login.php" --cookie /tmp/cookiejar.txt --cookie-jar /tmp/cookiejar.txt --data "username=$trueusername&password=$truepassword&param=$parameter" --insecure "https://portal.trueinternet.co.th/wifiauthen/login_result.php"
}

logout
login
sleep 5

while [ 1 ]; do
	#check web external site
	local up=`curl 'www.google.com/search?q=ip' | grep 'Client IP address:'` 
	if [ "$up" ]; then
		sleep $time
		logout
		login
	else
		logout
		login
	fi
	sleep 2
	rm /tmp/cookiejar.txt
	rm /tmp/ip.txt
done
